Python 시작하기

이 노트북은 처음으로 Python을 시작하는 사람이 실제로 명령어를 실행시키면서 기본 개념을 익히기 위한 문서이다.


In [1]:
print("Hello, universe!")


Hello, universe!
  • python 2

    • print 1
  • python 3

    • print(1)
  • python 2에서 python 3 문법을 사용하려면

    • from __future__ import print_function
    • 본 강의에서는 python 3 문법 사용

In [2]:
a = 3
b = 2 * a
a, b


Out[2]:
(3, 6)

Basic Types 기본 자료형

  • Boolean 부울리언
  • Integer 정수
  • Float 부동소수점
  • Complex 복소수
  • None

Boolean 부울리언


In [3]:
False, True


Out[3]:
(False, True)

In [4]:
test = (3 > 4)
test


Out[4]:
False

In [5]:
type(test)


Out[5]:
bool

Integer 정수


In [6]:
a = 4

In [7]:
type(a)


Out[7]:
int

Float 부동소수점


In [8]:
c = 2.14

In [9]:
type(c)


Out[9]:
float

Complex 복소수

  • complex number
  • 실수와 허수의 합으로 이루어지는 수
  • 허수단위 i(i2=-1이 되는 수의 하나)를 첨가
  • 복소수 a+bi에서 b≠0인 경우 a+bi를 허수라 하고, a=0이면 순허수

In [20]:
a = 1.5 + 0.5j   #j만 허수 변수로 인정이 되는데
a


Out[20]:
(1.5+0.5j)

In [13]:
a.real


Out[13]:
1.5

In [14]:
a.imag


Out[14]:
0.5

In [18]:
a.conjugate()


Out[18]:
(1.5-0.5j)

In [19]:
type(1. + 0j), type(5j)


Out[19]:
(complex, complex)

In [14]:
type(1. + 0j)


Out[14]:
complex

Casting 자료형 변환


In [21]:
float(1)


Out[21]:
1.0

In [23]:
7 * 3, type(7 * 3)


Out[23]:
(21, int)

In [24]:
7 * 3., type(7 * 3.)


Out[24]:
(21.0, float)

In [25]:
type((1 + 3j) * 5)   #뭐든 type이 섞이면 더 복잡한 형태로 합쳐지는구나


Out[25]:
complex

Division


In [30]:
# from __future__ import division

In [36]:
3 / 2, 10 / 3


Out[36]:
(1.5, 3.3333333333333335)

In [32]:
# without from __future__ import division
# 3 / 2   =>  1

In [37]:
3 // 2, 10 // 3


Out[37]:
(1, 3)

Power


In [35]:
2 ** 5, 3 ** 5, 2**10


Out[35]:
(32, 243, 1024)

Modulo


In [38]:
8 % 3, 10 % 3, 12 % 7, 10 % 2


Out[38]:
(2, 1, 5, 0)

Assignment


In [39]:
a = 1
a += 1
a


Out[39]:
2

In [40]:
a = 10
a -= 1
a


Out[40]:
9

In [41]:
a = 20
a *= 2
a


Out[41]:
40

In [42]:
a = 30
a /= 3
a


Out[42]:
10.0

Comparison 비교

$$ 2 > 1, \;\;\; 2 \geq 1, \;\;\; 2 = 1 $$

In [43]:
2 > 1, 2 >= 1, 2 == 1, 2 < 1


Out[43]:
(True, True, False, False)

Containers 고급 자료형

  • list 리스트
  • dictionary 사전
  • tuple 튜플
  • string 문자열

List 리스트


In [44]:
l = ['red', 'blue', 'green', 'black', 'white']
type(l)


Out[44]:
list

Indexing 인덱싱

  • container 유형의 자료에서 일부 자료만 뽑아내는 일

In [45]:
l[0]


Out[45]:
'red'

In [46]:
l[1]


Out[46]:
'blue'

In [47]:
l[-1]


Out[47]:
'white'

In [48]:
l[-2]


Out[48]:
'black'

Slicing 슬라이싱


In [49]:
l[2:4]


Out[49]:
['green', 'black']
  • l[start:stop:step]
    • start<= < stop
    • i = i + step
  • All slicing parameters are optional:

In [50]:
l[2:]


Out[50]:
['green', 'black', 'white']

In [51]:
l[:2]


Out[51]:
['red', 'blue']

In [54]:
l[::2], l[::3]


Out[54]:
(['red', 'green', 'white'], ['red', 'black'])
  • Lists are mutable
  • can be modified

In [55]:
l


Out[55]:
['red', 'blue', 'green', 'black', 'white']

In [56]:
l[0] = 'yellow'
l


Out[56]:
['yellow', 'blue', 'green', 'black', 'white']

In [57]:
l[2:4] = ['gray', 'purple']
l


Out[57]:
['yellow', 'blue', 'gray', 'purple', 'white']
  • list may have different types

In [58]:
l = [3.14, -200, 'hello']

In [60]:
l[0], l[1], l[2]


Out[60]:
(3.14, -200, 'hello')

Methods 메소드

  • Add, Remove

In [61]:
L = ['red', 'blue', 'green', 'black', 'white']

In [62]:
L.append('pink')

In [63]:
L


Out[63]:
['red', 'blue', 'green', 'black', 'white', 'pink']

In [64]:
L.pop() # removes and returns the last item


Out[64]:
'pink'

In [65]:
L


Out[65]:
['red', 'blue', 'green', 'black', 'white']

In [66]:
L.extend(['pink', 'gray']) # extend L, in-place

In [74]:
L


Out[74]:
['red',
 'blue',
 'green',
 'black',
 'white',
 'pink',
 'gray',
 ['pink', 'gray'],
 ['pink', 'gray']]

In [77]:
L = L[:-2]
L


Out[77]:
['red', 'blue', 'green', 'black', 'white']
  • Reverse

In [95]:
r = L[::-1]
r


Out[95]:
['white', 'black', 'green', 'blue', 'red']

In [79]:
r.reverse()

In [80]:
r


Out[80]:
['red', 'blue', 'green', 'black', 'white']

In [83]:
r2 = list(L)
r2


Out[83]:
['red', 'blue', 'green', 'black', 'white']

In [84]:
r2.reverse()   # in-place
r2


Out[84]:
['white', 'black', 'green', 'blue', 'red']
  • Concatenate and repeat lists

In [85]:
r, L


Out[85]:
(['red', 'blue', 'green', 'black', 'white'],
 ['red', 'blue', 'green', 'black', 'white'])

In [86]:
r + L


Out[86]:
['red',
 'blue',
 'green',
 'black',
 'white',
 'red',
 'blue',
 'green',
 'black',
 'white']

In [56]:
r


Out[56]:
['red', 'blue', 'green', 'black', 'white']

In [57]:
r * 2


Out[57]:
['red',
 'blue',
 'green',
 'black',
 'white',
 'red',
 'blue',
 'green',
 'black',
 'white']
  • Sort

In [96]:
sorted(r) # new object


Out[96]:
['black', 'blue', 'green', 'red', 'white']

In [97]:
r


Out[97]:
['white', 'black', 'green', 'blue', 'red']

In [99]:
r.sort()  # in-place

In [100]:
r


Out[100]:
['black', 'blue', 'green', 'red', 'white']
  • All methods
    • r. + press

In [102]:
#r.  +   tap을 해보면 methods가 나온다.

In [103]:
dir(r)


Out[103]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__delslice__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__setslice__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

String 문자열


In [104]:
s = 'Hello, how are you?'
s


Out[104]:
'Hello, how are you?'
  • Multi-line string

In [106]:
s = '''Hello,                 
       how are you
       doing'''
s


Out[106]:
'Hello,                 \n       how are you\n       doing'

In [107]:
s = """Hi,
what's up?"""
s


Out[107]:
"Hi,\nwhat's up?"

In [109]:
s = 'Hi, what's up?'
s


  File "<ipython-input-109-1c268f2f5ffd>", line 1
    s = 'Hi, what's up?'
                  ^
SyntaxError: invalid syntax
  • nested

In [110]:
s = "Hi, what's up?"
s


Out[110]:
"Hi, what's up?"
  • string is a container

In [111]:
a = "hello"

In [112]:
a[0]


Out[112]:
'h'

In [113]:
a[1]


Out[113]:
'e'

In [114]:
a[-1]


Out[114]:
'o'

In [115]:
a = "hello, world!"

In [116]:
a[3:6]


Out[116]:
'lo,'

In [117]:
a[2:10:2]


Out[117]:
'lo o'

In [118]:
a[::3]


Out[118]:
'hl r!'
  • immutable: cannot change

In [119]:
a[2] = 'z'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-119-d57c4312feba> in <module>()
----> 1 a[2] = 'z'

TypeError: 'str' object does not support item assignment

In [120]:
a


Out[120]:
'hello, world!'

In [121]:
a.replace('l', 'z')


Out[121]:
'hezzo, worzd!'

In [122]:
a


Out[122]:
'hello, world!'
  • format
    • string % argument
    • %d: integer
    • %f: float
    • %s: string

In [123]:
"x=%d" % 1


Out[123]:
'x=1'

In [124]:
"%s=%f" % ("pi", 3.14)


Out[124]:
'pi=3.140000'

Dictionary 사전


In [125]:
tel = {'emmanuelle': 5752, 'sebastian': 5578}
tel


Out[125]:
{'emmanuelle': 5752, 'sebastian': 5578}

In [126]:
tel['sebastian'], tel['emmanuelle']


Out[126]:
(5578, 5752)

In [127]:
tel['francis'] = 5915
tel


Out[127]:
{'emmanuelle': 5752, 'francis': 5915, 'sebastian': 5578}

In [128]:
tel.keys()


Out[128]:
['sebastian', 'francis', 'emmanuelle']

In [129]:
tel.values()


Out[129]:
[5578, 5915, 5752]

In [130]:
'francis' in tel


Out[130]:
True

Tuple 튜플


In [133]:
u = (0, 2)
u


Out[133]:
(0, 2)

In [134]:
t = 12345, 54321, 'hello!'
t


Out[134]:
(12345, 54321, 'hello!')

In [135]:
t[0]


Out[135]:
12345

In [140]:
t[0] = (1)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-140-9017e1fdb049> in <module>()
----> 1 t[0] = (1)

TypeError: 'tuple' object does not support item assignment

Reference, Mutable, Immutable


In [142]:
a = [1, 2, 3]
b = a
a, b


Out[142]:
([1, 2, 3], [1, 2, 3])

In [143]:
id(a), id(b)


Out[143]:
(172229768L, 172229768L)

In [144]:
id?

In [145]:
a[0] = 11

In [146]:
a


Out[146]:
[11, 2, 3]

In [147]:
b


Out[147]:
[11, 2, 3]

In [148]:
b[1] = "hi!"
b


Out[148]:
[11, 'hi!', 3]

In [149]:
a


Out[149]:
[11, 'hi!', 3]

In [150]:
a = [1, 'hi!', 3]
b = 1
a, b


Out[150]:
([1, 'hi!', 3], 1)

In [151]:
id(a), id(b)


Out[151]:
(172351240L, 31850120L)

zip


In [152]:
a = [1, 2, 3]
b = [10, 20, 30]

In [153]:
c = zip(a, b)
c


Out[153]:
[(1, 10), (2, 20), (3, 30)]

In [155]:
d = dict(c)
d


Out[155]:
{1: 10, 2: 20, 3: 30}

In [156]:
zip(*c)


Out[156]:
[(1, 2, 3), (10, 20, 30)]

In [157]:
zip(*zip(*c))


Out[157]:
[(1, 10), (2, 20), (3, 30)]

Code Line-Break 여러 줄로 나누어 쓰기

  • 리스트나 딕셔너리 정의, 함수 호출/정의 등의 경우에는 문법적으로 완료되지 않으면 그냥 다음 줄 사용 가능
  • 그렇지 않은 경우 backslash사용

In [162]:
a = [1, 2, 3,
    4, 5, 6]
a


Out[162]:
[1, 2, 3, 4, 5, 6]

In [166]:
a = 1 + 3 + 4 + 
    5 + 6 + 7


  File "<ipython-input-166-ba3a09e60c35>", line 1
    a = 1 + 3 + 4 +
                    ^
SyntaxError: invalid syntax

In [169]:
a = 1 + 3 + 4 + \
    5 + 6 + 7
a


Out[169]:
26

Control Flow 흐름 제어

  • if/elif/else
  • for/range
  • while/break/continue
  • enumerate
  • dictionary loop
  • list comprehension

If/elif/else


In [170]:
if 2**2 == 4:
    print("Obvious!")


Obvious!
  • Python Indentation 들여쓰기
    • space or tab
    • number of spaces: block level
    • convention: 4 spaces

In [171]:
a = 10
if a == 1:
    print(1)
elif a == 2:
    print(2)
else:
    print("A lot")


A lot

for/range


In [172]:
range(10)   # :10


Out[172]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [173]:
for i in range(4):
    print(i)


0
1
2
3

In [174]:
i


Out[174]:
3

In [175]:
range(5, 10)    # 5:10


Out[175]:
[5, 6, 7, 8, 9]

In [176]:
x = ["a", "b", "c", "d", "e"]
for i in range(1, 4):
    print(x[i])


b
c
d

In [177]:
for word in ['cool', 'powerful', 'readable']:
    print('Python is %s' % word)


Python is cool
Python is powerful
Python is readable

In [178]:
for xi in x[1:4]:
    print(xi)


b
c
d

In [179]:
print(x[1:4])


['b', 'c', 'd']

while/break/continue


In [180]:
z = 1 + 1j
while abs(z) < 100:
    z = z**2 + 1
    print(z, abs(z))
z


((1+2j), 2.23606797749979)
((-2+4j), 4.47213595499958)
((-11-16j), 19.4164878389476)
((-134+352j), 376.64306710730784)
Out[180]:
(-134+352j)

In [181]:
z = 1 + 1j
while abs(z) < 100:
    if z.imag < 0:     #허수가 음수면 나오는 거
        print("break!")
        break
    z = z**2 + 1
    print(z)
z


(1+2j)
(-2+4j)
(-11-16j)
break!
Out[181]:
(-11-16j)

In [184]:
a = [1, 0, 2, 4]
for element in a:
    if element == 0:
        continue
    print(1. / element)


1.0
0.5
0.25

Enumerate


In [186]:
words = ('nice', 'smart', 'lovely')
for i in range(len(words)):
    print((i, words[i]))


(0, 'nice')
(1, 'smart')
(2, 'lovely')

In [187]:
for i, item in enumerate(words):
    print((i, item))


(0, 'nice')
(1, 'smart')
(2, 'lovely')

Dictionary Loop


In [188]:
d = {'a': 1, 'b':1.2, 'c':1j}
d.items()


Out[188]:
[('a', 1), ('c', 1j), ('b', 1.2)]

In [189]:
for key, val in sorted(d.items()):
    print('Key: %s has vale: %s' % (key, val))


Key: a has vale: 1
Key: b has vale: 1.2
Key: c has vale: 1j

In [190]:
for item in sorted(d.items()):
    print('item', str(item))


('item', "('a', 1)")
('item', "('b', 1.2)")
('item', "('c', 1j)")

List Comprehensions


In [191]:
%%timeit
x = range(10000)
y = []
for i in x:
    y.append(i * 2)


100 loops, best of 3: 2.75 ms per loop

In [194]:
%%timeit
y = [i*2 for i in range(10000)]


1000 loops, best of 3: 1.26 ms per loop

Function 함수

  • definition 정의
  • parameter 인수
  • local, global 스코프
  • variable number of parameters
  • docstring

definition 함수의 정의

  • 콜론(:) 사용
  • 들여쓰기 (indentation)

In [195]:
def test():
    print('in test function')

In [196]:
test()


in test function

In [197]:
test()
test()
test()
test()


in test function
in test function
in test function
in test function

parameter 인수


In [198]:
def disk_area(radius):
    return 3.14 * radius * radius

In [199]:
disk_area(1.5)


Out[199]:
7.0649999999999995

In [200]:
def double_it(x):
    return x * 2

In [201]:
double_it(3)


Out[201]:
6

In [202]:
double_it()


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-202-51cdedbb81b0> in <module>()
----> 1 double_it()

TypeError: double_it() takes exactly 1 argument (0 given)

default parameter


In [203]:
def double_it(x=2):
    return x * 2

In [204]:
double_it(3)


Out[204]:
6

In [205]:
double_it()


Out[205]:
4

In [206]:
def slicer(seq, start=None, stop=None, step=None):
    return seq[start:stop:step]

In [207]:
rhyme = 'one fish, two fish, red fish, blue fish'.split()
rhyme


Out[207]:
['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']

In [208]:
slicer(rhyme)   # rhyme[::]


Out[208]:
['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']

In [209]:
slicer(rhyme, step=2)   # rhyme[::2]


Out[209]:
['one', 'two', 'red', 'blue']

In [210]:
slicer(rhyme, 1, step=2)    # rhyme[1::2]


Out[210]:
['fish,', 'fish,', 'fish,', 'fish']

In [211]:
slicer(rhyme, start=1, stop=4, step=2)   # rhyme[1:4:2]


Out[211]:
['fish,', 'fish,']

local variable


In [212]:
def try_to_modify(x, y, z):
    x = 23
    y.append(42)
    z = [99]   # new reference
    print(x)
    print(y)
    print(z)

In [213]:
a = 77    # immutable variable
b = [99]  # mutable variable
c = [28]

In [214]:
try_to_modify(a, b, c)


23
[99, 42]
[99]

In [215]:
print(a)
print(b)
print(c)


77
[99, 42]
[28]

In [216]:
x = 5
def addx(y):
    return x + y

In [217]:
addx(10)


Out[217]:
15

In [218]:
def setx(y):
    x = y
    print('x is %d' % x)

In [219]:
setx(10)


x is 10

In [220]:
x


Out[220]:
5

global variable


In [221]:
def setx(y):
    global x
    x = y
    print('x is %d' % x)

In [222]:
setx(10)


x is 10

In [223]:
x


Out[223]:
10

Variable number of parameters

  • *args: positional arguments (tuple)
  • **kwargs: keyword arguments (dictionary)

In [224]:
def variable_args(*args, **kwargs):
    print('args is', args)
    print('kwargs is', kwargs)

In [225]:
variable_args('one', 'two', x=1, y=2, z=3)


('args is', ('one', 'two'))
('kwargs is', {'y': 2, 'x': 1, 'z': 3})

Docstrings


In [226]:
def funcname(params):
    """Concise one-line sentence describing the function.
    Extended summary which can contain multiple paragraphs.
    """
    pass

In [227]:
funcname?

In [228]:
funcname.__doc__


Out[228]:
'Concise one-line sentence describing the function.\n    Extended summary which can contain multiple paragraphs.\n    '

None

  • 아무것도 출력하지 않거나
  • 아무것도 받지 않는 경우

In [229]:
def f():
    a = 1

In [230]:
x = f()
x

In [231]:
print(x)


None

is 비교

  • 같은 메모리를 가리키고 있는지 비교

In [232]:
a = 3.14 * 2
b = 6.28

In [233]:
a == b


Out[233]:
True

In [234]:
print(id(a), id(b))


(178235064L, 178235112L)

In [235]:
a is b


Out[235]:
False

In [236]:
a = None

In [237]:
# a == None <---  사용하지 말것! __eq__ overload 시 위험!
a is None, a is not None


Out[237]:
(True, False)

In [239]:
def f(x, y=None):
    if y is None:
        return x * x
    else:
        return x * y

In [240]:
f(10)


Out[240]:
100

In [241]:
f(10, 20)


Out[241]:
200

Package Import


In [242]:
import scipy

In [243]:
scipy.__file__


Out[243]:
'C:\\Anaconda3\\envs\\py27\\lib\\site-packages\\scipy\\__init__.pyc'
  • pakage alias
    • 패키지 이름이 길거나 다른 이름으로 사용하고 싶은 경우
    • import XXX as YY

In [244]:
import numpy as np
import scipy as sp
import pandas as pd
import sklearn as sk
import matplotlib as mpl
import matplotlib.pylab as plt
import seaborn as sns


---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-244-6f14e5e046db> in <module>()
      5 import matplotlib as mpl
      6 import matplotlib.pylab as plt
----> 7 import seaborn as sns

ImportError: No module named seaborn
  • 서브패키지 임포트

    • 자동 임포트

      • 상위 패키지를 임포트 하면 상위 패키지의 __init__.py 내부에서 하위 패키지를 임포트
      • 사용자가 하위 패키지를 추가로 임포트할 필요 없음
    • 수동 임포트

      • 메모리 절약을 위해 하위 패키지를 자동으로 임포트 하지 않음
      • 사용자가 필요한 서브패키지를 수동으로 임포트

In [245]:
sp.stats.norm.rvs(size=10)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-245-5b9458e4f472> in <module>()
----> 1 sp.stats.norm.rvs(size=10)

AttributeError: 'module' object has no attribute 'stats'

In [246]:
sp.constants.c


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-246-1041528b4e47> in <module>()
----> 1 sp.constants.c

AttributeError: 'module' object has no attribute 'constants'

In [247]:
import scipy.constants
sp.constants.c


Out[247]:
299792458.0

In [ ]: